#include <iostream>
#include <cstdio>
#include <cstring>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

#define ERR_EXIT(m) \
        do {\
            perror(m); \
            exit(EXIT_FAILURE); \
        } while(0)


int main() {
    int sock;
    struct sockaddr_in svrAddr, localAddr;
    socklen_t addrlen = sizeof(sockaddr);
    

    sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock < 0)
        ERR_EXIT("socket");
    
    memset(&svrAddr, 0, sizeof(svrAddr));
    svrAddr.sin_family = AF_INET;
    svrAddr.sin_port = htons(8888);
    svrAddr.sin_addr.s_addr = inet_addr("127.0.0.1");

    if (connect(sock, (sockaddr *)&svrAddr, sizeof(svrAddr)) < 0)
        ERR_EXIT("connect");
    
    if (getsockname(sock, (sockaddr *)&localAddr, &addrlen) < 0)
        ERR_EXIT("getsockname");

    std::cout << "ip = " << inet_ntoa(localAddr.sin_addr)
              << " port = " << ntohs(localAddr.sin_port) << std::endl;
    
    char sendBuf[1024] = {0};
    char recvBuf[1024] = {0};

    while (fgets(sendBuf, sizeof(sendBuf), stdin) != NULL)
    {
        write(sock, sendBuf, strlen(sendBuf));
        read(sock, recvBuf, sizeof(recvBuf));

        fputs(recvBuf, stdout);
        memset(sendBuf, 0, sizeof(sendBuf));
        memset(recvBuf, 0, sizeof(recvBuf));
    }

    close(sock);

    return 0;
    

    

}